<!--
 * @Descripttion: 订单管理
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-12 18:48:41
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-26 19:07:10
-->
<template>
  <div class="order-manager">
    <div class="control-box">
      <!-- control 操作区 START -->
      <e-control
        :search-form-options="formOptions"
        :search-label-width="'100px'"
        :btns="btns"
        @on-search="searchControlHandle"
        @on-refresh="refreshControlHandle"
        @change-height="changeControlHeight"
        @on-sync="syncHandle"
        @on-import="importHandle"
      ></e-control>
      <!-- control 操作区 END -->
    </div>
    <div class="table-box">
      <!-- table 数据表格 START -->
      <e-table
        :data="tableData"
        :columns="columns"
        stripe
        border
        :maxHeight="tableMaxHeight"
        style="width: 100%"
        @select="changeTableSelectData"
        @select-all="changeTableSelectAll"
        :current="pageData.pageNum"
        :total="pageData.total"
        @page-size-change="changePageSize"
        @page-current-change="changePageCurrent"
      >
        <template slot-scope="{ scope }" slot="operation">
          <el-button
            @click="checkHandle(scope.row)"
            type="warning"
            size="mini"
            icon="el-icon-view"
            plain
            >查看</el-button
          >
        </template>
      </e-table>
      <!-- table 数据表格 END -->
    </div>
    <!-- editDialog 编辑弹窗 START -->
    <el-dialog
      title="订单详情"
      :visible.sync="editDialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="80%"
    >
      <h4>订单信息</h4>
      <el-row style="margin: 10px 0">
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">订单编号：</el-col>
          <el-col :span="16">{{ orderDetailData.orderNo }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">供应商订单编号：</el-col>
          <el-col :span="16">{{ orderDetailData.supplierOrderNo }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">采购组织：</el-col>
          <el-col :span="16">{{ orderDetailData.purchasingOrganization }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">电商订单号：</el-col>
          <el-col :span="16">{{ orderDetailData.eshopNumber }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">下单人：</el-col>
          <el-col :span="16">{{ orderDetailData.purchasingPeople }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">手机号：</el-col>
          <el-col :span="16">{{ orderDetailData.purchasingPhone }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">收件人：</el-col>
          <el-col :span="16">{{ orderDetailData.addressee }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">收货地址：</el-col>
          <el-col :span="16">{{ orderDetailData.receivingAddress }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">联系电话：</el-col>
          <el-col :span="16">{{ orderDetailData.contactNumber }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">供应商信息：</el-col>
          <el-col :span="16">¥ {{ orderDetailData.supplierInfo }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">发票类型：</el-col>
          <el-col :span="16">¥ {{ orderDetailData.invoiceType }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">发票抬头：</el-col>
          <el-col :span="16">¥ {{ orderDetailData.invoiceTitle }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">财务组织：</el-col>
          <el-col :span="16">¥ {{ orderDetailData.financialOrganization }}</el-col>
        </el-col>
        <el-col :span="12" class="pd5 lineHeight20">
          <el-col :span="8" class="text-right">备注：</el-col>
          <el-col :span="16">{{ orderDetailData.remark }}</el-col>
        </el-col>
      </el-row>
      <h4>商品信息</h4>
      <e-table
        :data="orderDetailData.orderDetailList"
        :columns="columns2"
        :pageShow="false"
        stripe
        border
        :maxHeight="tableMaxHeight"
        style="width: 100%"
      >
        <template slot-scope="{ scope }" slot="priceOfficePicture">
          <el-button type="text" @click="handlePreview(scope.row.priceOfficePicture)" style="text-decoration: underline;">{{pictureName(scope.row.priceOfficePicture)}}</el-button>
        </template>
      </e-table>
    </el-dialog>
    <!-- editDialog 编辑弹窗 END -->
    <!-- 查看附件   -->
    <el-dialog :visible.sync="dialogPreviewVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import eControl from '@/components/e-control'
import { formOptions, btns } from './control'
import { columns, columns1, columns2 } from './columns'
import {
  // getList,
  getPurchaseType,
  getExport,
  syncOrderStatus,
  centrOrderInfor,
  queryHistoryOrderPageList,
  queryHistoryOrderDetail
} from '@/api/admin.api'
import { orderLogistics } from '@/api/supplier.api'
import {getFileInfo, queryDictionaryList} from '@/api/common.api'
import moment from 'moment'
export default {
  name: 'order-manager',
  components: {
    eControl,
  },
  props: {},
  data() {
    return {
      dialogPreviewVisible:false,
      dialogImageUrl:'',
      // 表单配置项
      formOptions,
      // 查询表单label宽度
      searchLabelWidth: '100px',
      // 查询表单
      searchFormData: {},
      // 按钮组
      btns,
      // 表格表头
      columns,
      // 配送表头
      columns1,
      // 商品信息表头
      columns2,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        current: 1,
        // 分页条数
        size: 10,
        // 数据总数
        total: 0,
      },
      // 表格选中数据
      tableSelectData: [],
      // 编辑框是否展示
      editDialogShow: false,
      // 订单详情数据
      orderDetailData: {},
      // 物流信息
      logisticsList: [],
      isLocalSupplier: '0',
      // 本地供应商物流信息
      localList: [],
    }
  },
  watch: {},
  filters: {
    formeTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ' '
    },
  },
  computed: {
    //表格最大高度
    tableMaxHeight() {
      return window.innerHeight - this.controlHeight - 160
    },
    pictureName () {
      return function (picture) {
        if (!picture) {
          return ''
        } else {
          const priceOfficePicture = JSON.parse(picture)
          return priceOfficePicture.name
        }
      }
    }
  },
  methods: {
    // 预览附件
    handlePreview (value) {
      const file = JSON.parse(value)
      // 获取附件信息
      getFileInfo(file.fileType,file.id).then(res=>{
        if (['image/png','image/jpeg'].includes(res.contextType)) {
          this.dialogImageUrl = res.url
          this.dialogPreviewVisible = true
        } else {
          // 下载
          document.location.href = res.url
        }
      })
    },
    // 查询订单状态option
    getOrderStatusOptions() {
      const param = {
        dictionaryType: 'order_state',
        dictionaryKey1: 'order',
        dictionaryKey2: 'eshop',
      }
      queryDictionaryList(param).then((res) => {
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.optional1
          optionObj.value = item.code
          if (this.formOptions[6].options) {
            this.$set(this.formOptions[6].options, index, optionObj)
          }
        })
      })
    },
    // 查询发票类型option
    getInvoiceTypeOptions() {
      const param = { dictionaryType: 'receiptType' }
      queryDictionaryList(param).then((res) => {
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.optional1
          optionObj.value = item.dictionaryKey1
          this.$set(this.formOptions[7].options, index, optionObj)
        })
      })
    },
    // 查询付款方式option
    getPaymentMethodOptions() {
      getPurchaseType('1').then((res) => {
        res.map((item, index) => {
          const optionObj = {}
          optionObj.label = item.branchName
          optionObj.value = item.id
          this.$set(this.formOptions[8].options, index, optionObj)
        })
      })
    },
    // 页面初始化
    init() {
      this.getTableData()
    },
    // 重置搜索条件
    refreshControlHandle(data) {
      this.searchFormData = data
    },
    // 搜索区动态高度
    changeControlHeight(height) {
      this.controlHeight = height
    },
    // 检索订单管理列表
    searchControlHandle(data) {
      this.searchFormData = data
      this.refreshPageCurrent()
    },
    // 请求订单管理列表
    getTableData() {
      if (this.searchFormData.time) {
        this.searchFormData.startTime = this.searchFormData.time[0]
        this.searchFormData.endTime = this.searchFormData.time[1]
      } else {
        this.searchFormData.startTime = ''
        this.searchFormData.endTime = ''
      }
      const newSearch = {
        purchaseType: 1,
        startTime: this.searchFormData.startTime,
        endTime: this.searchFormData.endTime,
        purchaseName: this.searchFormData.purchaseName,
        orderNo: this.searchFormData.orderNo,
        orderName: this.searchFormData.orderName,
        consignee: this.searchFormData.consignee,
        orderState: this.searchFormData.orderState,
        receiptType: this.searchFormData.receiptType,
        purchaseBranchId: this.searchFormData.payment,
        eshopNumber: this.searchFormData.eshopNumber,
        ...this.pageData,
      }
      queryHistoryOrderPageList(newSearch).then((res) => {
        const filter = this.$options.filters['formeTime']
        const newArr = []
        res.records.map((item) => {
          item.createTime = filter(item.createTime)
          newArr.push(item)
        })
        this.tableData = newArr
        this.pageData.total = res.total
      })
    },
    // 获取选中行数据
    changeTableSelectData(row) {
      this.tableSelectData = row
    },
    // 全选
    changeTableSelectAll(data) {
      this.tableSelectData = data
    },
    // 获取列表条数，查询数据
    changePageSize(size) {
      this.pageData.size = size
      this.getTableData()
    },
    // 获取当前分页，查询数据
    changePageCurrent(current) {
      this.pageData.current = current
      this.getTableData()
    },
    // 重置分页，查询数据
    refreshPageCurrent() {
      this.pageData.current = 1
      this.getTableData()
    },
    // 查看详情
    checkHandle(row) {
      this.isLocalSupplier = row.eshopNumber ? '0' : '1'
      centrOrderInfor(row.id).then((res) => {
        this.orderDetailData = res
        this.editDialogShow = true
      })
      queryHistoryOrderDetail(row.id)
        .then((res) => {
          if (res && res.length > 0) {
            if (this.isLocalSupplier === '0') {
              const result = res[0].track
              this.LogisticsList = result ? JSON.parse(result) : []
            } else {
              this.localList = res
            }
          }
        })
        .catch((err) => {
          console.log(err)
          if (err.code === -1) {
            this.logisticsList = []
            this.localList = []
          }
        })
    },
    // 保存下载文件
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        const link = document.createElement('a')
        const body = document.querySelector('body')
        link.href = window.URL.createObjectURL(blob)
        link.download = filename
        link.style.display = 'none'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      }
    },
    // 导出订单
    importHandle() {
      if (this.searchFormData.time) {
        this.searchFormData.startTime = this.searchFormData.time[0]
        this.searchFormData.endTime = this.searchFormData.time[1]
      }
      const newSearch = {
        purchaseType: 1,
        startTime: this.searchFormData.startTime
          ? this.searchFormData.startTime
          : '',
        endTime: this.searchFormData.endTime ? this.searchFormData.endTime : '',
        unitName: this.searchFormData.unitName
          ? this.searchFormData.unitName
          : '',
        orderNo: this.searchFormData.orderNo ? this.searchFormData.orderNo : '',
        consignee: this.searchFormData.consignee
          ? this.searchFormData.consignee
          : '',
        orderName: this.searchFormData.orderName
          ? this.searchFormData.orderName
          : '',
        orderState: this.searchFormData.orderState
          ? this.searchFormData.orderState
          : '',
        receiptType: this.searchFormData.receiptType
          ? this.searchFormData.receiptType
          : '',
        payment: this.searchFormData.payment ? this.searchFormData.payment : '',
      }
      getExport(newSearch).then((res) => {
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        this.saveAs(blob, '订单信息.xlsx')
      })
    },
    // 同步订单状态
    syncHandle() {
      if (this.tableSelectData.length === 0) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定',
        })
        return false
      }
      const ids = []
      this.tableSelectData.map((item) => {
        if (item.eshopNumber) {
          ids.push(item.eshopNumber)
        }
      })
      syncOrderStatus({ eshopNumbers: ids.toString() }).then((res) => {
        this.$message({
          message: '订单状态已同步',
          type: 'success',
        })
      })
    },
  },
  created() {},
  mounted() {
    this.getOrderStatusOptions()
    this.getInvoiceTypeOptions()
    this.getPaymentMethodOptions()
    this.init()
  },
}
</script>
<style lang="scss">
.control-box {
  margin-bottom: 10px;
}
.text-right {
  text-align: right;
}
.pd5 {
  padding: 5px;
}
.lineHeight20 {
  line-height: 20px;
}
h4 {
  line-height: 30px;
}
.order-manager .el-dialog__body {
  height: 70vh;
  overflow-y: auto;
}
</style>
